import router, { asyncRoutes } from './router'
import NProgress from 'nprogress' // 进度条包.start().done()两个方法
import 'nprogress/nprogress.css' // progress bar style
const whiteList = ['/login', '/404'] // no redirect whitelist 白名单
import store from '@/store'
import getPageTitle from '@/utils/get-page-title'

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    if (!store.getters.name) {
      // 调用user请求getUserInfoActions方法 得到数据 方法会return访问页面的权限
      const menus = await store.dispatch('user/getUserInfoActions')
      // 路由体系里要加入->用于页面跳转使用
      const myArr = asyncRoutes.filter(obj => {
        const myObj = menus.find(item => obj.path === '/' + item)
        if (myObj) return obj
        else return
      })
      // 拼接404为了解决 刷新 跳转404页面
      // router.addRoutes 这是异步任务
      router.addRoutes([...myArr, { path: '*', redirect: '/404', hidden: true }])
      // 存到vuex里面的->给左侧菜单栏生成使用
      store.commit('permission/SET_ROUTES', [...myArr, { path: '*', redirect: '/404', hidden: true }])
      // 强制跳转 replace 是否能回退
      // setTimeout(() => {
      next({
        path: to.path,
        replace: true
      })
      // }, 0)
    }
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  document.title = getPageTitle(router.currentRoute.meta.title)
  NProgress.done()
})
